<script setup>
import { ref } from 'vue'
import { getTeahProjList,getFileUploadUrl,addTeachProj,deleteTeachProj,changeTeachProj,getApprovalRecordList } from '@/api/teacher/teacher.js'
import { getAchievementLevel } from '@/api/router/achievemrntLevel'
import { useUserStore } from '@/stores'
import { NButton } from 'naive-ui'


/*获取成果级别列表*/
const typeOptions = ref()
const getLevel = async() => {
  const { data:res } = await getAchievementLevel()
  if(res.code === 1) {
    // console.log(res.data)
    typeOptions.value = res.data.map(item => ({label:item.level,value:item.id}))
    // console.log(typeOptions.value)
  }
  else if( res.code === 0) {
    alert(res.message)
  }
}
//调用获取成果级别方法
getLevel()

/* 分页 */
const currentPage = ref(1)
const page_size = ref(5)
const itemCount = ref(null)
const onUpdatePage = async() => {
  const jobNumber = userStore.jobNumber
  const pageSize = page_size.value
  const page = currentPage.value 
  const { data:res } = await getTeahProjList({jobNumber,pageSize,page})
  if (res.code  === 1) {
    data.value = res.data.rows
  }
  else if(res.code === 0) {
    alert(res.message)
  }
}

/*获取教师教学项目列表*/
const data = ref([])  //存储向后端请求回来的教学项目列表数据
const userStore = useUserStore()
const getData = async() => {
  const jobNumber = userStore.jobNumber
  const pageSize = page_size.value
  const { data:res } = await getTeahProjList({jobNumber,pageSize})
  if (res.code  === 1) {
    data.value = res.data.rows
    itemCount.value = res.data.total
  }
  else if(res.code === 0) {
    alert(res.message)
  }
}
//调用获取教师教学项目列表
getData()




//---表格信息---
const columns=[
  {title:'序号',key:'key',render:(_,index)=>`${index + 1}`,align:"center" },
  {title:'项目名称',key:'projectName',align:"center"},
  {title:'项目级别',key:'level',align:"center"},
  {title:'获批年度',key:'year' ,align:"center"},
  {title:'项目负责人',key:'leader' ,align:"center"},
  {title:'其他成员',key:'others' ,align:"center"},
  {title:'相关附件',key:'attachment',align:'center',render:row => {
    return h(NButton,{
      size: 'small', type:'info', quaternary: true, onClick: () => {
        const url = 'http://localhost:8080' + row.attachment
        window.open(url,"_blank")
      }
    },
    {default: () => row.attachment === null ? null : '查看'}
    )
  }},
  {title:'备注',key:'comment' ,align:"center"},
  {title:'审核',key:'check',align:'center',render:row => {
    return h(NButton,{
      size: 'small',type:'info',quaternary:true,onClick: async() => {
        if(row.status === "待提交") {
          current.value = 1
          currentStatus.value = "process"
          step1.value = "请提交申请"
          step2.value = null
          step3.value = null
          step4.value = null
        } else if(row.status === "待初审") {
          current.value = 2
          currentStatus.value = "process"
          step1.value = "已提交申请"
          step2.value = "审核中"
          step3.value = null
          step4.value = null
        } else if(row.status === "待复核") {
          current.value = 3
          currentStatus.value = "process"
          step1.value = "已提交申请"
          step2.value = "通过"
          step3.value = "审核中"
          step4.value = null
        } else if(row.status === "通过") {
          current.value = 4
          currentStatus.value = "process"
          step1.value = "已提交申请"
          step2.value = "通过"
          step3.value = "通过"
          step4.value = "项目审核完成"
        }
        else if(row.status === "驳回修改" || row.status === "不予认定") {
          const achievementId = row.codeNumber
          const { data: res } = await getApprovalRecordList({achievementId})
          if(res.code === 1) {
            approvalRecord.value = res.data[0]
            if(approvalRecord.value.phase === "初审") {
              current.value = 2
              currentStatus.value = "error"
              step1.value = "已提交申请"
              step2.value = approvalRecord.value.opinion
              step3.value = null
              step4.value = null
            } else if(approvalRecord.value.phase === "复核") {
              current.value = 3
              currentStatus.value = "error"
              step1.value = "已提交申请"
              step2.value = "通过"
              step3.value = approvalRecord.value.opinion
              step4.value = null
            }
          } else alert(res.msg)
        }
        showCheckModal.value=true
      }
    },
    {default: () => row.status}
    )
  }},
  {title:'操作',key:'operate' ,align:"center",width:'200',render:row=>{
    if(row.statusId === 1 || row.statusId === 5 || row.statusId === 6 ) {
      return [
    h(NButton,{
      size: 'small', type: 'primary', secondary: true, onClick: () => {
                showChangeModal.value=true;
                changeForm.value.codeNumber=row.codeNumber
                changeForm.value.projectName=row.projectName;
                changeForm.value.achievementLevelId=row.achievementLevelId;
                if(row.year != null) {
                  changeForm.value.year = Date.parse(row.year)
                } else {
                  changeForm.value.year = null
                }
                changeForm.value.leader=row.leader;
                changeForm.value.attachment=row.attachment;
                changeForm.value.others=row.others;
                changeForm.value.comment=row.comment;
                }
              },{default:()=>('修改')}
    ),
    h(NButton,{
      size: 'small', type: 'error', secondary: true, onClick: async() => {
                const id = row.codeNumber
                const { data:res } = await deleteTeachProj(id)
                if(res.code === 1) {
                  alert('删除成功')
                } else {
                  alert('删除失败')
                }
                onUpdatePage()
                }
              },
              {default:()=>('删除')}
    ),
    h(NButton,{
      size: 'small', type: 'info', secondary: true, onClick: async() => {
                let msg = ''
                if(row.projectName === null) msg  += '项目名称为空;'
                if(row.achievementLevelId === null) msg  += '项目级别为空;'
                if(row.year === null) msg  += '获批年度为空;'
                if(row.leader === null) msg  += '项目级别为空;'
                if(row.others === null) msg  += '其他成员为空;'
                if(row.attachment === null) msg  += '相关附件为空;'
                if(msg === '') {
                  const temp = {
                    codeNumber: row.codeNumber,
                    statusId: 2
                  }
                  const {data:res} = await await changeTeachProj(JSON.stringify(temp))
                  if(res.code === 1) {
                    alert('提交成功')
                  } else alert(res.msg)
                } else alert(msg)
                onUpdatePage()
                }
              },
              {default:()=>('提交')}
    )
    ]
    }
    else{
      return h(NButton,{
      size: 'small', type: 'primary', secondary: true, onClick: () => {
                showViewModal.value=true;
                viewForm.value.projectName=row.projectName;
                viewForm.value.level=row.level;
                viewForm.value.year = row.year
                viewForm.value.leader=row.leader;
                viewForm.value.attachment=row.attachment;
                viewForm.value.others=row.others;
                viewForm.value.comment=row.comment;
                }
              },{default:()=>('查看')}
    )
    }
  }},
]



/*添加教学项目模态框*/
const showAddModal = ref(false)
const addFormRef=ref(null)
//获取表项中收集到的值的对象
const addForm=ref({
  projectName:null,
  level: null,
  year: null,
  leader: null,
  others: null,
  attachment: null,
  comment: null,
  jobNumber: userStore.jobNumber
})
//验证表项的规则
const formRules={
  projectName:{required: true, message: '请填写项目名称', trigger: 'blur'},
  achievementLevelId:{type: "number",required: true, message: '请选择项目类别', trigger: 'blur'},
  year:{type: "number",required: true, message: '请填写获批年度', trigger: 'blur'},
  leader:{required: true, message: '请填写项目负责人', trigger: 'blur'},
  others:{required: true, message: '请填写其他成员', trigger: 'blur'},
  attachment:{required: true, message: '请填写相关附件', trigger: 'blur'},
}


const addProject = () => {
  showAddModal.value = true
  //将表单项的值先制空
  addForm.value.projectName = null
  addForm.value.achievementLevelId = null
  addForm.value.year = null
  addForm.value.leader = null
  addForm.value.others = null
  addForm.value.attachment = null
  addForm.value.comment = null 
}

/*文件上传*/
//1.通过ref函数的到ref对象
const inputRef = ref(null)
const showA = ref(false)
const fileUpload = async(temp) => {
  console.log(inputRef.value.files[0])
  //获取上传文件
  const file = inputRef.value.files[0]
  const { data:res } = await getFileUploadUrl(file)
  console.log(res)
  if(res.code === 1) {
    if(temp === 'add') {
      addForm.value.attachment = res.data
    } else if (temp === 'change') {
      changeForm.value.attachment = res.data
    }
    alert('文件上传成功')
    showA.value = true
  }
  else if(res.data === 0) {
    alert(res.message)
  }

}

/* 保存教学项目 */
const saveAdd = async() => {
  console.log(addForm.value)
  if(addForm.value.year != null) {
    const date = new Date(addForm.value.year)
    const year = date.getFullYear()
    addForm.value.year = year
  }
  let msg = ''
  if(addForm.value.projectName === null) msg  += '项目名称为空;'
  if(addForm.value.achievementLevelId === null) msg  += '项目级别为空;'
  if(addForm.value.year === null) msg  += '获批年度为空;'
  if(addForm.value.leader === null) msg  += '项目级别为空;'
  if(addForm.value.others === null) msg  += '其他成员为空;'
  if(addForm.value.attachment === null) msg  += '相关附件为空;'
  if(msg === '') {
    const { data: res } = await addTeachProj(addForm.value)
    if(res.code === 0) alert(res.msg)
    else{
      onUpdatePage()
      showAddModal.value = false
    }
  }
  else{
    alert(msg)
  }
}


/* 修改教学项目模态框 */
const showChangeModal = ref(false)
const changeForm = ref({
  codeNumber:null,
  projectName:null,
  achievementLevelId: null,
  year: null,
  leader: null,
  others: null,
  attachment: null,
  comment: null,
})
const changeFormRef=ref(null)
const changeFormRules = {
  projectName:{required: true, message: '请填写项目名称', trigger: 'blur'},
  achievementLevelId:{type: "number",required: true, message: '请选择项目类别', trigger: 'blur'},
  year:{type: "number",required: true, message: '请填写获批年度', trigger: 'blur'},
  leader:{required: true, message: '请填写项目负责人', trigger: 'blur'},
  others:{required: true, message: '请填写其他成员', trigger: 'blur'},
  attachment:{required: true, message: '请填写相关附件', trigger: 'blur'},
}
const saveChange = async() => {
  if(changeForm.value.year != null) {
    const date = new Date(changeForm.value.year)
    const year = date.getFullYear()
    changeForm.value.year = year
  }
  let msg = ''
  if(changeForm.value.projectName === null) msg  += '项目名称为空;'
  if(changeForm.value.achievementLevelId === null) msg  += '项目级别为空;'
  if(changeForm.value.year === null) msg  += '获批年度为空;'
  if(changeForm.value.leader === null) msg  += '项目级别为空;'
  if(changeForm.value.others === null) msg  += '其他成员为空;'
  if(changeForm.value.attachment === null) msg  += '相关附件为空;'
  if(msg === '') {
    const temp = JSON.stringify(changeForm.value)
    const {data:res} = await changeTeachProj(temp)
    if(res.code === 0) alert(res.msg)
    else{
      onUpdatePage()
      showChangeModal.value=false
    }
  }
  else{
    alert(msg)
  }
}

/* 查看教学项目模态框 */
const showViewModal = ref(false)
const viewForm = ref({
  projectName:null,
  achievementLevelId: null,
  year: null,
  leader: null,
  others: null,
  attachment: null,
  comment: null,
})

/* 审批进度模态框 */
const showCheckModal = ref(false)
const current = ref(2)
const currentStatus = ref("process")
const step1 = ref(null)
const step2 = ref(null)
const step3 = ref(null)
const step4 = ref(null)
const approvalRecord = ref(null)


/* 条件查询成果信息 */
const year = ref(null)
const formValue = ref({
  jobNumber: userStore.jobNumber,
  year: null,
  projectName: null,
})
const searchAchievement = async() => {
  if(year.value != null) {
    const date = new Date(year.value)
    const switchYear = date.getFullYear()
    formValue.value.year = switchYear
  } else formValue.value.year = null
  const { data: res } = await getTeahProjList(formValue.value)
    if(res.code === 1) {
      data.value = res.data.rows
      itemCount.value = res.data.total
    }
    else if(res.code === 0) {
      alert(res.message)
    }
}


</script>

<template>
    <div class="title">教学项目信息登记</div>
    <div class="content">
      <div class="function">
        <n-space style="margin-bottom: 5px;">
        <n-button type="primary" tertiary @click="addProject" style="padding: 0 4px; font-size: 16px;">
          <template #icon>
            <n-icon>
              <img src="@/assets/edit_add.png" alt="新增" style="height: 16px; margin: 0;">
            </n-icon>
          </template>
          新增
          </n-button>
      </n-space>
      <n-space style="margin-bottom: 5px;">
      <n-form
        inline
        label-placement="left"
        :model="formValue"
        size="small"
      >
        <n-form-item label="项目名称" path="projectName">
          <n-input v-model:value="formValue.projectName" placeholder="输入项目名称" />
        </n-form-item>
        <n-form-item label="年份" path="year">
          <n-date-picker v-model:value="year" type="year" style="width:100px"/>
        </n-form-item>
        <n-form-item>
          <n-button attr-type="button" @click="searchAchievement" type="info">
            查询
          </n-button>
        </n-form-item>
      </n-form>
      </n-space>
      </div>
      <n-data-table
        :columns="columns"
        :data="data"
        bordered
        :single-line="false"
        size='small'
      />
      <div class="pagination">
        <n-pagination v-model:page="currentPage"
                    @update-page="onUpdatePage"
                    :page-size="page_size"
                    :item-count="itemCount"/>
      </div>
      <!-- 添加教学项目模态框 -->
      <n-modal v-model:show="showAddModal" :auto-focus="false" :mask-closable="false">
        <n-card style="width: 480px;"
              title="添加教学项目"
              bordered
              closable
              @close="showAddModal=false"
              size="small"
              role="dialog"
              aria-modal="true">
          <n-form :model="addForm"
                ref="addFormRef"
                :rules="formRules"
                style="padding-top: 10px;"
                label-placement="left"
                label-width="100"
                label-align="right">
            <n-form-item label="项目名称" path="projectName">
              <n-input v-model:value="addForm.projectName" clearable />
            </n-form-item>
            <n-form-item label="项目级别" path="achievementLevelId">
               <n-select v-model:value="addForm.achievementLevelId" placeholder="请选择" :options="typeOptions" />
            </n-form-item>
            <n-form-item label="获批年度" path="year">
              <n-date-picker type="date" v-model:value="addForm.year" style="width:400px" format="yyyy"/>
            </n-form-item>
            <n-form-item label="项目负责人" path="leader">
              <n-input v-model:value="addForm.leader" clearable/>
            </n-form-item>
            <n-form-item label="其他成员" path="others">
              <n-input v-model:value="addForm.others" clearable/>
            </n-form-item>
            <n-form-item label="相关附件" path="attachment">
              <form @submit.prevent="fileUpload('add')" >
                <input type="file" class="fileInput" ref="inputRef"/>
                <input type="submit" value="上传" />
                <a v-show="showA" :href = "'http://localhost:8080'+ addForm.attachment" target="_blank">查看</a>
              </form>
            </n-form-item>
            <n-form-item label="备注" path="comment">
              <n-input v-model:value="addForm.comment" clearable/>
            </n-form-item>
          </n-form>
          <!-- 对话框底部控制按钮 -->
          <template #footer>
          <div style="float: right">
            <n-space>
              <n-button size="small" secondary type="primary" @click="saveAdd">保存</n-button>
              <n-button size="small" secondary @click="showAddModal=false">取消</n-button>
            </n-space>
          </div>
          </template>
        </n-card>
      </n-modal>


      <!-- 修改教学项目模态框 -->
      <n-modal v-model:show="showChangeModal">
        <n-card style="width: 480px;"
              title="修改教学项目"
              bordered
              closable
              @close="showChangeModal=false"
              size="small"
              role="dialog"
              aria-modal="true">
          <n-form :model="changeForm"
                ref="changeFormRef"
                :rules="changeFormRules"
                style="padding-top: 10px;"
                label-placement="left"
                label-width="100"
                label-align="right">
          <n-form-item label="项目名称" path="projectName">
            <n-input v-model:value="changeForm.projectName" clearable />
          </n-form-item>
          <n-form-item label="项目级别" path="achievementLevelId">
             <n-select v-model:value="changeForm.achievementLevelId" :options="typeOptions" />
          </n-form-item>
          <n-form-item label="获批年度" path="year">
            <n-date-picker v-model:value="changeForm.year" style="width:400px" format="yyyy"/>
          </n-form-item>
          <n-form-item label="项目负责人" path="leader">
            <n-input v-model:value="changeForm.leader" clearable/>
          </n-form-item>
          <n-form-item label="其他成员" path="others">
            <n-input v-model:value="changeForm.others" clearable/>
          </n-form-item>
          <n-form-item label="相关附件" path="attachment">
            <form @submit.prevent="fileUpload('change')" >
                <input type="file" class="fileInput" ref="inputRef"/>
                <input type="submit" value="上传" />
                <a v-show="changeForm.attachment" :href = "'http://localhost:8080'+ changeForm.attachment" target="_blank">查看</a>
              </form>
          </n-form-item>
          <n-form-item label="备注" path="comment">
            <n-input v-model:value="changeForm.comment" clearable/>
          </n-form-item>
        </n-form>
        <!-- 对话框底部控制按钮 -->
        <template #footer>
          <div style="float: right">
            <n-space>
              <n-button size="small" secondary type="primary" @click="saveChange">保存</n-button>
              <n-button size="small" secondary @click="showChangeModal=false">取消</n-button>
            </n-space>
          </div>
        </template>
        </n-card>
      </n-modal>

      <!-- 查看教学项目模态框 -->
      <n-modal v-model:show="showViewModal">
        <n-card style="width: 480px;"
              title="查看教学项目"
              bordered
              closable
              @close="showViewModal=false"
              size="small"
              role="dialog"
              aria-modal="true">
          <n-form style="padding-top: 10px;"
                label-placement="left"
                label-width="100"
                label-align="right">
          <n-form-item label="项目名称:" path="projectName">
            <span>{{ viewForm.projectName }}</span>
          </n-form-item>
          <n-form-item label="项目级别:" path="level">
            <span>{{ viewForm.level }}</span>
          </n-form-item>
          <n-form-item label="获批年度:" path="year">
            <span>{{ viewForm.year }}</span>
          </n-form-item>
          <n-form-item label="项目负责人:" path="leader">
            <span>{{ viewForm.leader }}</span>
          </n-form-item>
          <n-form-item label="其他成员:" path="others">
            <span>{{ viewForm.others }}</span>
          </n-form-item>
          <n-form-item label="相关附件:" path="attachment">
                <a :href = "'http://localhost:8080'+ viewForm.attachment" target="_blank">查看</a>
          </n-form-item>
          <n-form-item label="备注:" path="comment">
            <span>{{ viewForm.comment }}</span>
          </n-form-item>
        </n-form>
        </n-card>
      </n-modal>

      <!-- 审批进度模态框 -->
      <n-modal v-model:show="showCheckModal" preset="dialog" title="Dialog" style="width: 1000px;height: 200px;" >
        <template #header>
          <div style="font-size: 25px;">审核</div>
        </template>
        <div style="margin-top: 30px;">
          <n-space vertical>
            <n-steps :current="Number(current)" :status="currentStatus">
              <n-step
                title="提交"
                :description="step1"
              />
              <n-step
                title="初审"
                :description="step2"
              />
              <n-step
                title="复核"
                :description="step3"
              />
              <n-step
                title="已完成"
                :description="step4"
              />
            </n-steps>
          </n-space>
        </div>  
      </n-modal>
    </div>
    <div style="color: red; font-size: 13px;">
      说明：1.附件格式为jpg、bmp、png、pdf等文件
      <br>
      &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;2.不支持压缩包上传
      <br>
      &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;3.大小限制在30M以内
    </div>
</template>
<style scoped>
.pagination {
  float: right;
  padding-top: 50px;
}
.title{
  color: rgb(5,93,163);
  text-align: center;
  font-size:22px;
  font-family: "Microsoft Yahei","Helvetica Neue", Helvetica, Arial, sans-serif;
  border-bottom: 1px solid rgb(193, 217, 237);
  margin-bottom: 5px;
}

/* 样式穿透在vue3中的两种写法
第一种
 :deep(.n-data-table-th__title){
   font-weight: 600;
 }*/

/* 第二种 */
::v-deep .n-data-table-th__title{
  font-weight: 600;
}

::v-deep .n-button__icon{
  margin:0 1px 0 0;
}
.fileInput {
  width: 180px;
}

span {
  width: 364px;
  padding: 5px;
  border: 1px solid rgb(184, 182, 182);
}
::v-deep .n-data-table-td{
  padding: 6px;
}

.function{
  display: flex;
  justify-content: space-between;
}
</style>
